package com.inspur.edp.ai.flow.api;

import com.inspur.edp.common.type.enhanced.EnhancedServiceLoader;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lizhaorui
 * @date 2025/11/25
 * @description
 */
public class ServiceContainer {

    public static Map<Class, Object> SERVICE_MAP = new HashMap<>();
    
    public static <T> T getService(Class<T> requiredType) {
        if (!SERVICE_MAP.containsKey(requiredType)) {
            synchronized (requiredType) {
                List<Object> objectList = EnhancedServiceLoader.loadFile("META-INF/services/" + requiredType.getName(), ServiceContainer.class.getClassLoader());
                if (objectList != null && objectList.size() > 0) {
                    if (objectList.size() == 1) {
                        SERVICE_MAP.put(requiredType, objectList.get(0));
                    } else if (objectList.size() == 2) {
                        boolean find = false;
                        for (Object object : objectList) {
                            if (!object.getClass().getName().startsWith("com.inspur.edp.ai.flow")) {
                                SERVICE_MAP.put(requiredType, object);
                                find = true;
                                break;
                            }
                        }
                        if (!find) {
                            SERVICE_MAP.put(requiredType, objectList.get(0));
                        }
                    } else {
                        throw new RuntimeException("find has more 2 implements " + requiredType.getName());
                    }
                } else {
                    throw new RuntimeException("not find service " + requiredType.getName());
                }
            }
        }
        return (T) SERVICE_MAP.get(requiredType);
    }

}